<?php
if(!has_permission(PERM_WRITE_NEWS)) exit();
$news_id = "";
if(isset($_POST["news_id"]) && $_POST["news_id"] != "") $news_id = secure_user_input_int($_POST["news_id"]);
if(isset($_GET["news_id"]) && $_GET["news_id"] != "" && $news_id == "") $news_id = secure_user_input_int($_GET["news_id"]);

if(!isset($_POST["title"])) $_POST["title"] = "";
if(!isset($_POST["text"])) $_POST["text"] = "";

if($news_id != "" && ($_POST["title"] == "" || $_POST["text"] == "")) {
 $r = db_query("SELECT * FROM news WHERE id='".secure_mysql_int($news_id)."'");
 $v = mysql_fetch_array($r);
 $_POST["title"] = $v["subject"];
 $_POST["text"] = $v["text"];
 $_POST["public"] = ($v["flags"] & FLAG_RELEASED) ? "1" : "0";
}


if(isset($_GET["action"]) && $_GET["action"] == "save") {
 $c_date = time(NULL);
 
 $saved = 0;
 
 if($news_id != "") {
  $r = db_query("SELECT * FROM news WHERE id='".secure_mysql_int($news_id)."'");
  $v = mysql_fetch_array($r);
  if($v != NULL) {
   $fl = secure_user_input_int($v["flags"]);
   if(isset($_POST["public"]) && $_POST["public"] == "1") $fl |= (FLAG_RELEASED); else $fl &=~(FLAG_RELEASED);
   db_query("UPDATE news SET subject='".secure_mysql_string($_POST["title"])."', date='".$c_date."', text='".secure_mysql_string($_POST["text"])."',flags=".$fl." WHERE id='".secure_mysql_int($news_id)."'");
   $saved = 1;
  }
 }

 if(!$saved) {
  $fl = 0;
  if(isset($_POST["public"]) && $_POST["public"] == "1") $fl |= FLAG_RELEASED;
  db_query("INSERT INTO news (id, subject, author, date, text, tags, flags) VALUES ('', '".secure_mysql_string($_POST["title"])."', '".secure_mysql_string($_SESSION["user"])."', '".$c_date."', '".secure_mysql_string($_POST["text"])."', '', ".$fl.")");
 }
 
 $r = db_query("SELECT id FROM news WHERE date='".$c_date."' AND author='".secure_mysql_string($_SESSION["user"])."'");
 $v = mysql_fetch_array($r);
 $news_id = $v["id"];
}

?>

<h1>News verfassen</h1>
<form action="index.php?filter=new&amp;action=save" method="POST">
<input type="hidden" name="news_id" value="<?php echo $news_id; ?>"><br>

<table class="write_news">
 <tr>
  <td>Titel</td>
  <td><input type="text" name="title" value="<?php echo $_POST["title"]; ?>"></td>
 </tr>
 <tr>
  <td>Text</td>
  <td><textarea name="text"><?php echo $_POST["text"]; ?></textarea></td>
 </tr>
 <tr>
  <td>Optionen</td>
  <td><input type="checkbox" name="public" value="1" <?php echo (isset($_POST["public"]) && $_POST["public"] == "1") ? "checked='checked'" : "";?>>Ver&ouml;ffentlicht</td>
 </tr>
 <tr>
  <td>&nbsp;</td>
  <td><input type="submit" value="Speichern"></td>
 </tr>
</table>
</form>

<?php
?>
